package nc.appcan.bill.sync;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import nc.appcan.sppub.pub.MABillFunAction;
import nc.bs.framework.common.RuntimeEnv;
import nc.itf.uap.pf.AppCanBillItf;

public class AnnotateSyncTool {
	public static final String NCHOME =RuntimeEnv.getInstance().getNCHome()+"/modules/uap/META-INF/classes/";
	
	static {
	
		initBillFuncService();
	}
	public static AppCanBillItf  getServiceBillClass(String functype){
		AppCanBillItf itf = ServiceSyncCache.INSTANCE.getBillfuncmap().get(functype);
		return itf;
	}

	

	private static void initBillFuncService(){
		try {
			List<Class<?>> list = getClasses("nc.appcan.bill.function");
			for (Class<?> cla:list){
				String classname = cla.getName();
				if(classname.contains("$"))continue;
				if(cla.newInstance() instanceof AppCanBillItf){
					MABillFunAction action =cla.getAnnotation(MABillFunAction.class);
					if(action!=null)ServiceSyncCache.INSTANCE.getBillfuncmap().put(action.value(), (AppCanBillItf)cla.newInstance());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	 private  static List<Class<?>> getClasses(String packagename) throws Exception{  
		
		 String url = NCHOME+packagename.replace(".", "/"); 
		 List<Class<?>> list = new ArrayList<Class<?>>();  
		 File dir =  new File(url);
		 if (!dir.exists()) return list;   
        for (File f : dir.listFiles()) {  
            String name = f.getName();  
            if (name.endsWith(".class")) {  
            	list.add(Class.forName(packagename + "." + name.substring(0, name.length() - 6)));  
            }  
        } 
	       return list;  
	 }  
	
}
